package com.ysd.lis.service.bak.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.common.Result;
import com.ysd.lis.entity.bak.LabRptresultBak;
import com.ysd.lis.entity.lab.LabItemDict;
import com.ysd.lis.entity.lab.LabMaininfo;
import com.ysd.lis.entity.lab.LabRptresult;
import com.ysd.lis.mapper.bak.LabRptresultBakMapper;
import com.ysd.lis.mapper.lab.LabItemDictMapper;
import com.ysd.lis.mapper.lab.LabMaininfoMapper;
import com.ysd.lis.mapper.lab.LabRptresultMapper;
import com.ysd.lis.service.bak.LabRptresultBakService;
import com.ysd.lis.service.lab.LabMaininfoService;
import com.ysd.lis.service.lab.LabRptresultService;
import com.ysd.lis.service.lab.impl.LabRptresultCalcServiceImpl;
import com.ysd.util.ToolsUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 检验业务表 服务实现类
 * </p>
 *
 * @author WH
 * @since 2024-11-26
 */
@Service
public class LabRptresultBakServiceImpl extends ServiceImpl<LabRptresultBakMapper, LabRptresultBak> implements LabRptresultBakService {

    @Autowired
    LabMaininfoMapper labMaininfoMapper;
    @Autowired
    LabMaininfoService labMaininfoService;
    @Autowired
    LabRptresultService labRptresultService;
    @Autowired
    LabRptresultMapper labRptresultMapper;
    @Autowired
    LabItemDictMapper labItemDictMapper;
    @Autowired
    LabRptresultCalcServiceImpl labRptresultCalcService;
    @Override
    public Result updateRptResultBatchNew(List<LabRptresult> list) {
        //分组
        Map<List<Object>, List<LabRptresult>> rptResultMap = list.stream().collect(Collectors.groupingBy(s -> Arrays.asList(s.getSampleda(), s.getRptGroup(), s.getSampleNo(), s.getOrgId())));

        //取rptResultMap的第一个Key
        List<Object> mainInfolist = rptResultMap.keySet().stream().findFirst().get();
        Timestamp sampleda = null;
        String rptGroup = "";
        String sampleNo = "";
        String orgId  = "";
        if (ToolsUtils.isNotEmpty(mainInfolist.get(0))) {
            sampleda = (Timestamp) mainInfolist.get(0);
        }
        if (ToolsUtils.isNotEmpty(mainInfolist.get(1))) {
            rptGroup = String.valueOf(mainInfolist.get(1));
        }
        if (ToolsUtils.isNotEmpty(mainInfolist.get(2))) {
            sampleNo = String.valueOf(mainInfolist.get(2));
        }
        if (ToolsUtils.isNotEmpty(mainInfolist.get(3))) {
            orgId = String.valueOf(mainInfolist.get(3));
        }
        //按照分组后的数据生成labMaininfo数据
        LabMaininfo labMaininfo = null;
        String format = DateUtil.format(sampleda, "yyyy-MM-dd");
        Timestamp startTime = Timestamp.valueOf(format + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(format + " 23:59:59");
        //标本号查询
        LambdaQueryWrapper<LabMaininfo> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(LabMaininfo::getDelFlag, 0)
                .eq(LabMaininfo::getRptGroup, rptGroup)
                .ge(LabMaininfo::getSampleda, startTime)
                .le(LabMaininfo::getSampleda, endTime)
                .eq(LabMaininfo::getSampleNo, sampleNo)
                .eq(LabMaininfo::getOrgId, orgId);
        List<LabMaininfo> maininfoList1 = labMaininfoMapper.selectList(queryWrapper3);
        if (ToolsUtils.isNotEmpty(maininfoList1)) {
            labMaininfo = maininfoList1.get(0);
        }
        //无工作列表新建工作列表
        if (null == labMaininfo) {
            labMaininfo = new LabMaininfo();
            labMaininfo.setRptGroup(rptGroup);
            labMaininfo.setSampleda(startTime);
            labMaininfo.setSampleNo(sampleNo);
            labMaininfo.setTestTime(new Timestamp(System.currentTimeMillis()));
            labMaininfo.setIsChk(new BigDecimal(0));
            labMaininfo.setOrgId(orgId);
            LambdaQueryWrapper<LabMaininfo> lambdaQueryWrappers = new LambdaQueryWrapper<>();
            lambdaQueryWrappers.eq(LabMaininfo::getSampleNo, sampleNo)
                    .eq(LabMaininfo::getRptGroup, rptGroup)
                    .eq(LabMaininfo::getSampleda, startTime)
                    .eq(LabMaininfo::getOrgId, orgId)
                    .eq(LabMaininfo::getDelFlag, 0);
            boolean b = labMaininfoService.saveOrUpdate(labMaininfo, lambdaQueryWrappers);
        }
        BigDecimal isChk = labMaininfo.getIsChk();
        if (ToolsUtils.isNotEmpty(isChk) && isChk.intValue() > 0) {
            return Result.fail("已审核");
        }
        //去重之后要更新到结果表中的数据
        List<LabRptresult> labRptresultList = rptResultMap.get(mainInfolist).stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(LabRptresult::getItemNo))), ArrayList::new));
        //查工作列表结果
        LambdaQueryWrapper<LabRptresult> queryWrapper5 = new LambdaQueryWrapper<>();
        queryWrapper5.eq(LabRptresult::getDelFlag, 0)
                .eq(LabRptresult::getRptGroup, rptGroup)
                .eq(LabRptresult::getOrgId, orgId)
                .ge(LabRptresult::getSampleda, startTime)
                .le(LabRptresult::getSampleda, endTime)
                .eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo());
        List<LabRptresult> rptresultList = labRptresultService.list(queryWrapper5);
        List<LabRptresult> saveOrUpdateResultList = new ArrayList<>();

        for (LabRptresult instrResult : labRptresultList) {
            LabRptresult labRptresult;
            Optional<LabRptresult> rptresultOptional = rptresultList.stream().filter(rpt -> rpt.getItemNo().equals(instrResult.getItemNo())).findFirst();
            if (rptresultOptional.isPresent()) {
                labRptresult = rptresultOptional.get();
            } else {
                labRptresult = new LabRptresult();
                labRptresult.setSampleda(startTime);
                labRptresult.setRptGroup(instrResult.getRptGroup());
                labRptresult.setSampleNo(labMaininfo.getSampleNo());
                labRptresult.setItemNo(instrResult.getItemNo());
                labRptresult.setItemNa(instrResult.getItemNa());
                labRptresult.setMaininfoId(labMaininfo.getId());
                labRptresult.setOrgId(orgId);
                labRptresult.setDisplayOrder(instrResult.getDisplayOrder());

            }
            labRptresult.setTestResult(instrResult.getTestResult());
            if(ToolsUtils.isNotEmpty(instrResult.getTestResult())){
                labRptresult.setIsResult(1);
            }else {
                labRptresult.setIsResult(0);
            }
            saveOrUpdateResultList.add(labRptresult);
        }//接口结果循环完毕
        if (ToolsUtils.isNotEmpty(saveOrUpdateResultList)) {
            boolean isSaveOrupdate = labRptresultService.saveOrUpdateBatch(saveOrUpdateResultList);
            //工作列表结果
            LambdaQueryWrapper<LabRptresult> queryWrapper6 = new LambdaQueryWrapper<>();
            queryWrapper6.eq(LabRptresult::getDelFlag, 0)
                    .eq(LabRptresult::getRptGroup, rptGroup)
                    .eq(LabRptresult::getOrgId, orgId)
                    .ge(LabRptresult::getSampleda, startTime)
                    .le(LabRptresult::getSampleda, endTime)
                    .eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo());
            List<LabRptresult> rptResultList = labRptresultService.list(queryWrapper6);
            /*文字结果处理*/
            LabMaininfo finalLabMaininfo = labMaininfo;
            /*查询报告项目备用*/
            LambdaQueryWrapper<LabItemDict> _labitemdictQuery = new LambdaQueryWrapper<>();
            _labitemdictQuery.eq(LabItemDict::getRptGroup, labMaininfo.getRptGroup());
            _labitemdictQuery.eq(LabItemDict::getDelFlag, 0);
            _labitemdictQuery.eq(LabItemDict::getEnable, 1);
            _labitemdictQuery.orderByAsc(LabItemDict::getSeq);
            List<LabItemDict> itemList = labItemDictMapper.selectList(_labitemdictQuery);
            /*文字结果*/
            labRptresultCalcService.CalcTextResultV1(labMaininfo, rptResultList, itemList);
            /*结果二次处理*/
            labRptresultCalcService.CalcTransResultV1(labMaininfo, rptResultList, itemList);
            //计算项目处理
            labRptresultCalcService.CalcFormulaItemResultV1(labMaininfo, rptResultList,itemList);

            /*计算危急值*/
            labRptresultCalcService.CalcItemDictCriticalV1(labMaininfo, rptResultList, itemList);

            /*计算结果标识特殊规则*/
            labRptresultCalcService.CalcItemDictSpecialRulesV1(finalLabMaininfo, rptResultList);

            /*计算完成 更新 结果*/
            labRptresultService.saveOrUpdateBatch(rptResultList);

            //如果finalLabMaininfo下得所有rptResultList得isResult为1，则finalLabMaininfo得isResult为1
            this.calcIsResult(labMaininfo, rptResultList);
            return Result.succ(rptResultList.get(0));

        }else {
            return Result.fail("保存失败");
        }
    }


    private void calcIsResult(LabMaininfo labMaininfo, List<LabRptresult> rptresultlist) {
//        LambdaQueryWrapper<LabRptresult> _labrptresultmapper = new LambdaQueryWrapper<>();
//        _labrptresultmapper.eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo());
//        _labrptresultmapper.eq(LabRptresult::getRptGroup, labMaininfo.getRptGroup());
//        _labrptresultmapper.eq(LabRptresult::getSampleda, labMaininfo.getSampleda());
//        _labrptresultmapper.eq(LabRptresult::getDelFlag, 0);
//        List<LabRptresult> rptresultlist = labRptresultMapper.selectList(_labrptresultmapper);
        //如果labMaininfo下得所有rptresultlist得isResult为1，则finalLabMaininfo得isResult为1
        if (ToolsUtils.isNotEmpty(rptresultlist)) {
            List<LabRptresult> alarmList = rptresultlist.stream().filter(p -> ToolsUtils.isNotEmpty(p.getIsAlarm()) && p.getIsAlarm().equals(1)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(alarmList)) {
                labMaininfo.setIsAlarm(1);
            } else {
                labMaininfo.setIsAlarm(0);
            }
            List<LabRptresult> _lst = rptresultlist.stream().filter(p -> (ToolsUtils.isEmpty(p.getIsResult())||p.getIsResult() == 0)).collect(Collectors.toList());
            if (ToolsUtils.isEmpty(_lst)) {
                labMaininfo.setIsResult(1);
                labMaininfoService.updateById(labMaininfo);
            }
        }


    }
}
